package org.skywind.WindSearch.Filter;

import java.io.File;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.skywind.WindSearch.SearchManager;
import org.skywind.WindSearch.dao.SearchAction;
import org.skywind.WindSearch.util.Guest;
import org.skywind.xml.DOMUtil;
import org.w3c.dom.Document;

public class BaseFilter implements javax.servlet.Filter{
	private int pagesize = 12;
	private String defaultHost;
	private String defaultLanguage;
	private SearchManager sm;
	private SearchAction sa;
	private ServletContext app;
	
	public void destroy() {
		this.defaultHost = null;
		this.defaultLanguage =null;
		this.sa =null;
		this.sm =null;
		this.app=null;
	}

	public void doFilter(ServletRequest Srequest, ServletResponse Sresponse, FilterChain chain) throws IOException, ServletException {
		Srequest.setCharacterEncoding("utf-8");
		HttpServletRequest request=(HttpServletRequest)Srequest;
		HttpSession session=request.getSession();
		Guest sr = (Guest) session.getAttribute("guest");
		if (sr == null) {
			sr = new Guest(sm, sa, pagesize,request.getLocalAddr());
			session.setAttribute("guest", sr);
		}
		request.setAttribute("talk", sr.getLanguage());
		chain.doFilter(Srequest, Sresponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		Document doc;
		app = filterConfig.getServletContext();
		try {
			this.defaultHost = filterConfig.getInitParameter("Default-Host");
			this.defaultLanguage = filterConfig.getInitParameter("Default-Language");
			String conf = filterConfig.getInitParameter("Config");
			File file = new File(filterConfig.getServletContext().getRealPath(conf));
			if(file.exists())
				doc = DOMUtil.loadXML(file);//本地配置文件
			else
				doc = DOMUtil.loadXML(conf);//远程XML配置文件
			////////////////////////////////
			sm = new SearchManager();
			sm.setConfig(doc);
			app.setAttribute("system", sm);
			
			////////////////////////////////
			sa = new SearchAction(doc);
			app.setAttribute("dbaction", sa);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
